package com.littleken.logistics.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.littleken.logistics.pojo.Role;
import com.littleken.logistics.pojo.RoleExample;
import com.littleken.logistics.pojo.User;
import com.littleken.logistics.pojo.UserExample;
import com.littleken.logistics.service.RoleService;
import com.littleken.logistics.service.UserService;
import com.littleken.logistics.utils.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.littleken.logistics.pojo.UserExample.Criteria;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/adminPage")
    public String adminPage(){
        return "adminPage";
    }

    /**
     * 数据库测试，分页查询所有user
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @ResponseBody
    @RequestMapping("/list")
    public PageInfo<User> list(@RequestParam(defaultValue = "1")Integer pageNum,
                               @RequestParam(defaultValue = "10")Integer pageSize,
                               String keyword) {
        //开启插件分页
        PageHelper.startPage(pageNum, pageSize);
        //创建条件查询对象
        UserExample example = new UserExample();

        //StringUtils:common-lang3包中的工具类 可以快速处理各种string问题
        if (StringUtils.isNotBlank(keyword)) {//keyword判空
            //keyword既可以是账号也可以是真实姓名
            //用户名模糊查询
            Criteria criteria1 = example.createCriteria();//构建查询条件
            criteria1.andUsernameLike("%" + keyword + "%");

            //真实姓名模糊查询
            Criteria criteria2 = example.createCriteria();
            criteria2.andRealnameLike("%" + keyword + "%");

            //默认就是第一次创建的条件，所以只需or一次第二个条件
            example.or(criteria2);

            //角色名模糊查询
            Criteria criteria3 = example.createCriteria();
            criteria3.andRolenameLike("%" + keyword + "%");

            // 把第三个条件也OR进来
            example.or(criteria3);


        }

        //进行查询
        List<User> users = userService.selectByExample(example);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo;
    }

    /**
     * 返回新增修改页面
     * @param m
     * @param userId
     * @return
     */
    @RequestMapping("/adminEdit")
    public String adminEdit(Model m, Long userId) {

       //如果是修改，肯定带着userid过来，就先查询出来
        if (userId != null) {
            User user = userService.selectByPrimaryKey(userId);
            m.addAttribute("user", user);
        }

        // 查询出所有角色，用于新增/修改页面
        RoleExample example = new RoleExample();
        List<Role> roles = roleService.selectByExample(example);

        m.addAttribute("roles", roles);

        return "adminEdit";
    }

    @ResponseBody //返回json数据
    @RequestMapping("/delete")
    public JsonData  delete(Long userId){
        int i = userService.deleteByPrimaryKey(userId);
        JsonData msg;
        if (i==1){
            msg = JsonData.success("删除成功");
            System.out.println(msg.getMsg());
        }else {
            msg = JsonData.fail("删除失败，拉闸");
        }
        return msg;
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("/insert")
    public JsonData insert(User user) {
        System.out.println(user);
        //设置用户创建时间
        user.setCreateDate(new Date());

        // 使用UUID生成5位盐
        String salt = UUID.randomUUID().toString().substring(0, 5);
        //使用盐和密码进行3次MD5加密
        Md5Hash newPassword = new Md5Hash(user.getPassword(), salt, 3);

       //把加密好的密码存到数据库
        user.setSalt(salt);
        user.setPassword(newPassword.toString());

        int row = userService.insert(user);

        JsonData msg ;
        if (row == 1) {
            msg = JsonData.success("新增成功");
        }else {
            msg = JsonData.fail("新增失败，再次拉闸");
        }

        return msg;

    }


    //更新和新增其实就差一点点
    @ResponseBody
    @RequestMapping("/update")
    public JsonData update(User user) {
        System.out.println(user);
        String salt = UUID.randomUUID().toString().substring(0, 5);
        // 加密
        Md5Hash newPassword = new Md5Hash(user.getPassword(), salt, 3);

        user.setSalt(salt);
        user.setPassword(newPassword.toString());

        int row = userService.updateByPrimaryKeySelective(user);

        JsonData msg ;
        if (row == 1) {
            msg = JsonData.success("修改成功");
        }else {
            msg = JsonData.fail("修改失败，再次拉闸");
        }

        return msg;

    }

    /**
     * 用户名查重
     * @param username
     * @return
     */
    @RequestMapping("/checkUsername")
    @ResponseBody
    public boolean checkUsername(String username) {

        UserExample example = new UserExample();
        Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);

        //查重
        List<User> users = userService.selectByExample(example);
        //前台validate校验插件必须要求返回boolean，不能返回其他东西
        return users.size() == 0 ? true : false;
    }
}
